package com.ecar.api.rest.common;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ecar.api.rest.AbstractResource;
import com.ecar.api.service.common.impl.ActivityServiceImpl;
import com.ecar.api.support.util.Props;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.common.annotation.ResponseFilter;
import com.ecar.common.dto.DataBean;
import com.ecar.common.exception.MyException;
import com.ecar.common.util.JSONUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.entity.Address;
import com.ecar.core.common.entity.Coupon;
import com.ecar.core.common.entity.CouponActivities;
import com.ecar.core.driver.entity.Complaint;
import com.ecar.core.driver.entity.ModelSet;
@Controller
@Scope("prototype")
@Path("/activity")
public class ActivityController extends AbstractResource{
	
	@Autowired
	public ActivityServiceImpl activityService;
	/**
	 * 获取发布活动
	 * @author paul
	 * @return
	 */
	@ResponseFilter(target=CouponActivities.class,fields={})
	@GET
	@Path("/{passengerId}/sendActivities")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean sendActivities(@PathParam("passengerId") String passengerId) {
		try {
			if(passengerId.equals(null) || passengerId.trim().equals(""))
				return new DataBean(400,new JSONObject(),"参数有误！");
			
			List<CouponActivities> couponActivitiesList=activityService.queryCouponActivities();
			List<Coupon> couponList= activityService.selectByUserId(passengerId);
			for(CouponActivities couponActivities:couponActivitiesList){
			
//				String couponId=coupon.getCouponId();
				if(couponList.size()<=0){
					couponActivities.setStatus(CouponActivities.STATUS_OVER);//2:未领取
					continue;
				}
				for(Coupon coupon:couponList){
					if(couponActivities.getId().equals(coupon.getCouponId())){
						couponActivities.setStatus(CouponActivities.STATUS_ACTIVE);//1:已领取
						break;
					}else{
						couponActivities.setStatus(CouponActivities.STATUS_OVER);//2:未领取
					}
				}
				
			}
			
			return new DataBean(200,couponActivitiesList,"成功获取所有活动！");
			
		} catch (Exception e) {
			log.info("发布活动获取失败！");
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"获取发布活动失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 领取优惠卷
	 * @author paul
	 * @return
	 */
	@POST
	@Path("/receiveCoupon")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean receiveCoupon(JSONObject param) {
		try {
			if(!parse(param) && this.fields==null) return new DataBean(400, new JSONObject(),"参数错误，领取优惠卷失败。");
			Coupon coupon = new Coupon();
			coupon.setId(UuidUtils.getUUID());
			coupon.setCreateTime(new Date());
			coupon.setCouponId(this.fields.getString("activityId"));
			coupon.setUserId(this.fields.getString("userId"));
			coupon.setStatus(Coupon.NOT_USED);
			Coupon cp=activityService.selectByCouponActIdAndUserId(this.fields.getString("activityId"), this.fields.getString("userId"));
			if(cp!=null){
				return new DataBean(401,new JSONObject(),"你已领取优惠卷，不能重复领取！");
			}
			
			CouponActivities couponActivities=activityService.selectByPrimaryKey(this.fields.getString("activityId"));
			if(couponActivities.getStatus()==CouponActivities.STATUS_OVER){
				return new DataBean(400,new JSONObject(),"活动已结束！");
			}
			synchronized(this) {
				if(couponActivities.getCouponCount()==1){
					couponActivities.setStatus(CouponActivities.STATUS_OVER);
					activityService.updateByPrimaryKeySelective(couponActivities);//更改为结束
				}
				int couponCount=couponActivities.getCouponCount()-1;//优惠劵减1
				activityService.updateCouponCountByActivityId(this.fields.getString("activityId"), couponCount);
			}
			boolean  bl=activityService.pullCoupon(coupon);
			if(bl==false){
				return new DataBean(400,new JSONObject(),"领取优惠卷失败，数据库插入异常！");
			}
			return new DataBean(200,new JSONObject(),"恭喜您，领取到一张优惠卷！");
			
		} catch (Exception e) {
			log.info("领取优惠卷失败！");
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"领取优惠卷失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 用户获取自己的优惠卷list
	 * @author paul
	 * @return
	 */
	@ResponseFilter(target=CouponActivities.class,fields={})
	@GET
	@Path("/{passengerId}/userCoupon")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean queryUserCoupon(@PathParam("passengerId") String passengerId) {
		try {
			if(passengerId.equals(null) || passengerId.trim().equals("")){
				return new DataBean(400,new JSONObject(),"参数异常");
			}
			List<CouponActivities> couponList=activityService.selectCouponByUserId(passengerId);
			return new DataBean(200,couponList,"获取优惠卷成功！");
			
		} catch (Exception e) {
			log.info("获取优惠卷失败！");
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"获取优惠卷失败，服务器异常。");
			}
		}
	}
}
